package com.kandinfo.base.common.util;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 图片压缩处理
 * @author 
 */
public class ImgCompress {
	
	private final static Logger LOGGER = LoggerFactory.getLogger(ImgCompress.class);
	
	/*private Image img;
	private int width;
	private int height;
	
	*//**
	 * 
	 * @param weight    	压缩后最大宽度
	 * @param length		压缩后最大长度
	 * @param fromPath		图片源路径
	 * @param toPath		图片压缩后存放路径
	 *//*
	public static void compress (int weight ,int length ,String fromPath ,String toPath){
		ImgCompress imgCom;
		try {
			imgCom = new ImgCompress(fromPath);
			imgCom.resizeFix(weight, length ,toPath);
		} catch (IOException e) {
			LOGGER.error("图片文件读取出错！"+fromPath,e);
		}  
	}
	
	
	*//**
	 * 构造函数
	 * @throws IOException 
	 *//*
	private ImgCompress(String fileName) throws IOException {
		File file = new File(fileName);
		img = ImageIO.read(file);
		width = img.getWidth(null);    // 得到源图宽
		height = img.getHeight(null);  // 得到源图长
		    
	}
	*//**
	 * 按照宽度还是高度进行压缩
	 * @param w int 最大宽度
	 * @param h int 最大高度
	 * @param toPath 
	 *//*
	private void resizeFix(int w, int h, String toPath) {
		if (width / height > w / h) {
			resizeByWidth(w,toPath);
		} else {
			resizeByHeight(h,toPath);
		}
	}
	*//**
	 * 以宽度为基准，等比例放缩图片
	 * @param w int 新宽度
	 * @param toPath 
	 *//*
	private void resizeByWidth(int w, String toPath) {
		int h = (int) (height * w / width);
		resize(w, h,toPath);
	}
	*//**
	 * 以高度为基准，等比例缩放图片
	 * @param h int 新高度
	 * @param toPath 
	 *//*
	private void resizeByHeight(int h, String toPath) {
		int w = (int) (width * h / height);
		resize(w, h,toPath);
	}
	*//**
	 * 强制压缩/放大图片到固定的大小
	 * @param w int 新宽度
	 * @param h int 新高度
	 * @param toPath 
	 *//*
	private void resize(int w, int h, String toPath)  {
		FileOutputStream out = null;
		try {
			// SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢
			BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); 
			image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
			File destFile = new File(toPath);
			out = new FileOutputStream(destFile); // 输出到文件流
			// 可以正常实现bmp、png、gif转jpg
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(image); // JPEG编码
		
			
		} catch (Exception e) {
			LOGGER.error("",e);
		}finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					LOGGER.error("",e);
				}
			}
		}
		
	}*/
	
	/**
	 * 
	 * 
	 * 压缩图片
	 * 
	 * @param srcFilePath			源图片路径
	 * @param descFilePath			目标图片路径
	 * @param qality				压缩比率    0~1范围内
	 * @param times					缩小倍数
	 * @return
	 */
	@SuppressWarnings("static-access")
	public static boolean compressPic(String srcFilePath, String descFilePath,float qality ,int times) {
		if (qality > 1 || qality <= 0) {
			LOGGER.error("压缩比率不正确！(0~1范围内)   "+qality);
			return false;
		}
		if (StringUtils.isBlank(srcFilePath) || StringUtils.isBlank(descFilePath)) {
			return false;
		}
		
		File file = null;
		BufferedImage src = null;
		FileOutputStream out = null;
		ImageWriter imgWrier;
		ImageWriteParam imgWriteParams;
		
		
		String fileType = descFilePath.substring(descFilePath.lastIndexOf('.') + 1, descFilePath.length());

		// 指定写图片的方式为 jpg
		imgWrier = ImageIO.getImageWritersByFormatName(fileType).next();
		imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
		// 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
		imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
		// 这里指定压缩的程度，参数qality是取值0~1范围内，
		imgWriteParams.setCompressionQuality(qality);
		imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
		ColorModel colorModel = ColorModel.getRGBdefault();
		// 指定压缩时使用的色彩模式
		imgWriteParams.setDestinationType(
				new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));
		
		
		imgWriteParams.setSourceSubsampling(times, times, 0, 0);

		try {
			
			file = new File(srcFilePath);
			src = ImageIO.read(file);
			out = new FileOutputStream(descFilePath);

			imgWrier.reset();
			// 必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何
			// OutputStream构造
			imgWrier.setOutput(ImageIO.createImageOutputStream(out));
			// 调用write方法，就可以向输入流写图片
			imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
			out.flush();
			
		} catch (Exception e) {
			LOGGER.error("写入图片异常",e);
			return false;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					LOGGER.error("关闭流异常",e);
				}
			}
		}
		return true;
	}
	
	/**
	 * demo
	 * @param args
	 */
	public static void main(String[] args) {
		//compress(400, 400, "D://1.jpg", "D://2-1.jpg");
		compressPic( "D://img/1.jpg", "D://img/1-2.jpg",0.9f,3);
	}
}